package com.eryos.android.cigarettecounter.database;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBConnector {
	
	public static final String TAG = "DBConnector";

    protected final Context context;      
	protected DatabaseAdministrator dbHelper;
    protected SQLiteDatabase db;

    
    public static final String 	DATABASE_NAME 	= "eryos.db";
    public static final int 	DATABASE_VERSION= 8;
    
    public static final String 	DATABASE_TABLE 	= "smoke_table";
    public static final String 	ROWID_COLUMN 	= "_id";
    public static final String 	TIME_COLUMN 	= "smoke_time";
    public static final String 	REASON_COLUMN 	= "smoke_reason";
    public static final String 	PRICE_COLUMN  	= "smoke_valid";

    public static final String DATABASE_CREATE =
        "CREATE TABLE "+DATABASE_TABLE+" ( "
	        + ROWID_COLUMN 	   + " INTEGER PRIMARY KEY AUTOINCREMENT, "
	        + TIME_COLUMN   + " DATETIME DEFAULT CURRENT_TIMESTAMP, "
	        + REASON_COLUMN + " TEXT,"
	        + PRICE_COLUMN  + " TEXT"
        + ");";

    public static final String DATABASE_DROP = "DROP TABLE IF EXISTS "+DATABASE_TABLE;

    
    /**
     * 
     * @param ctx
     */
    public DBConnector(Context ctx) {
        this.context = ctx;
        
        open();
    }
    
    /**
     * Open the Database connection
     * @return DBConnector used to request database
     * @throws SQLException
     */
    public final DBConnector open() throws SQLException {    	
        if ( db == null || ! db.isOpen() ){
        	Log.w(getClass().getSimpleName(), "Open DB connection");
        	dbHelper = new DatabaseAdministrator(context);
        	db = dbHelper.getWritableDatabase();
        }
        return this;
    }

    /**
     * Close the connection to Database
     */
    public void close() {    	
    	if ( db.isOpen() ){
    		Log.w(getClass().getSimpleName(), "Close DB connection");
    		db.close();
    		dbHelper.close();    
    	}
    }

    /** ************************************************************************** **/    

    /**
	 * 
	 * @param sql
	 * @return
	 */
	public Cursor executeQuery(String sql){
		return db.rawQuery(sql, null);
	}
    
    /** ************************************************************************** **/    
    
    /**
     * Used for DDL operation on database (create, update, delete)
     */
    private static class DatabaseAdministrator extends SQLiteOpenHelper {
        /**
         * 
         * @param context 
         */
    	DatabaseAdministrator(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
 
    	@Override
    	public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion 
                  + " to "
                  + newVersion + ", which will destroy all old data");
            db.execSQL(DATABASE_DROP);
            onCreate(db);
        }
    }
}